define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

  var Controller = {
    index: function () {
      // 初始化表格参数配置
      Table.api.init({
        extend: {
          index_url: 'wdsxh/diy_page/index' + location.search,
          add_url: 'wdsxh/diy_page/add',
          edit_url: 'wdsxh/diy_page/edit',
          del_url: 'wdsxh/diy_page/del',
          multi_url: 'wdsxh/diy_page/multi',
          import_url: 'wdsxh/diy_page/import',
          table: 'wdsxh_diy_page',
        }
      });

      var table = $("#table");

      // 初始化表格
      table.bootstrapTable({
        url: $.fn.bootstrapTable.defaults.extend.index_url,
        pk: 'id',
        sortName: 'id',
        columns: [
          [
            { checkbox: true },
            { field: 'id', title: __('Id') },
            {
              field: 'page_name',
              title: __('Page Name')
            },
            { field: 'status', title: __('Status'), searchList: { "home": __('Status home'), "custom": __('Status custom') }, formatter: Table.api.formatter.status },
            { field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
            { field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
            {
              field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [
                {
                  name: 'adopt',
                  text: '设为首页',
                  title: '设为首页',
                  confirm: '页面类型确认设为首页吗？',
                  classname: 'btn btn-xs btn-info btn-view btn-ajax',
                  url: 'wdsxh/diy_page/setHome',
                  hidden: function (row) {
                    if (row.status != 'home') {
                      return false;
                    } else {
                      return true;
                    }
                  },
                  refresh: true
                },
              ],
            }
          ]
        ]
      });
      table.on('post-body.bs.table', function (e, settings, json, xhr) {
        $(".btn-editone,.btn-edit,.btn-add").data("area", ["100%", "100%"]);
      });
      // 为表格绑定事件
      Table.api.bindevent(table);
    },
    recyclebin: function () {
      // 初始化表格参数配置
      Table.api.init({
        extend: {
          'dragsort_url': ''
        }
      });

      var table = $("#table");

      // 初始化表格
      table.bootstrapTable({
        url: 'wdsxh/diy_page/recyclebin' + location.search,
        pk: 'id',
        sortName: 'id',
        columns: [
          [
            { checkbox: true },
            { field: 'id', title: __('Id') },
            {
              field: 'deletetime',
              title: __('Deletetime'),
              operate: 'RANGE',
              addclass: 'datetimerange',
              formatter: Table.api.formatter.datetime
            },
            {
              field: 'operate',
              width: '140px',
              title: __('Operate'),
              table: table,
              events: Table.api.events.operate,
              buttons: [
                {
                  name: 'Restore',
                  text: __('Restore'),
                  classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                  icon: 'fa fa-rotate-left',
                  url: 'wdsxh/diy_page/restore',
                  refresh: true
                },
                {
                  name: 'Destroy',
                  text: __('Destroy'),
                  classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                  icon: 'fa fa-times',
                  url: 'wdsxh/diy_page/destroy',
                  refresh: true
                }
              ],
              formatter: Table.api.formatter.operate
            }
          ]
        ]
      });

      // 为表格绑定事件
      Table.api.bindevent(table);
    },

    add: function () {
      new Vue({
        el: '#diy',
        data: {
          jsonData: jsonData,
          selectedIndex: -1,
          defaultData: defaultData,
          curItem: {},
          // 选择url start
          dialogData: null,
          dialogSelecturl: false,
          currmenuidx: 'Inlay',//索引
          fcall: null,// 回调
          dialogform: {
            param1: '',
            param2: '',
          }
          // 选择url end
        },
        error: '',
        methods: {
          /**
           * 新增组件
           * @param key
           */
          handleAdd: function (key) {
            if (!this.onCheckAddwebview(key)) {
              return false;
            }
            // 复制默认diy组件数据
            var data = $.extend(true, {}, defaultData[key]);
            // 新增到diy列表数据
            this.jsonData.items.push(data);

            // 编辑当前选中的元素
            this.handleEdit(this.jsonData.items.length - 1);
          },

          /**
           * 拖动diy元素更新当前索引
           * @param e
           */
          onDragItemEnd: function (e) {
            this.handleEdit(e.newIndex);
          },

          /**
           * 验证新增Diy组件
           * @param key
           */
          onCheckAddwebview: function (key) {
            // 验证webview组件只能存在一个
            if (key === 'webview') {
              if (this.jsonData.items.length != 0) {
                Toastr.error('webview不能和其他组件一起使用');
                return false;
              }
            } else {
              for (var index in this.jsonData.items) {
                if (this.jsonData.items.hasOwnProperty(index)) {
                  var item = this.jsonData.items[index];
                  if (item.type === 'webview') {
                    Toastr.error('webview不能和其他组件一起使用');
                    return false;
                  }
                }
              }
            }
            return true;
          },

          /**
           * 编辑当前选中的Diy元素
           * @param index
           */
          handleEdit: function (index) {
            // 记录当前选中元素的索引
            this.selectedIndex = index;
            // 当前选中的元素数据
            this.curItem = this.selectedIndex == -1 ? this.jsonData.page : this.jsonData.items[this.selectedIndex];
            // 设置选中标签
            if (!this.curItem.activeName) this.curItem.activeName = "first"
          },

          // 监听富文本中值的变化
          handleInputChange() {
            this.curItem.params.content = $(".form-editor .editor").html()
          },

          // 获取当前时间
          getCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
          },

          /**
           * 复制diy元素
           * @param index
           */
          onCopyItem: function (index) {
            var _this = this;
            // 复制默认diy组件数据
            var data = $.extend(true, {}, _this.jsonData.items[index]);
            // 新增到diy列表数据
            this.jsonData.items.push(data);

            // 编辑当前选中的元素
            this.handleEdit(this.jsonData.items.length - 1);
          },
          /**
           * diy元素上移
           * @param index
           */
          onMoveUp: function (index) {
            if (0 == index) {
              return;
            }
            this.jsonData.items[index] = this.jsonData.items.splice(index - 1, 1, this.jsonData.items[index])[0];
            this.selectedIndex = index - 1
          },

          /**
           * diy元素下移
           * @param index
           */
          onMoveDown: function (index) {
            if (this.jsonData.items.length - 1 == index) {
              return;
            }
            this.jsonData.items[index] = this.jsonData.items.splice(index + 1, 1, this.jsonData.items[index])[0];
            this.selectedIndex = index + 1
          },
          /**
           * 删除diy元素
           * @param index
           */
          onDeleleItem: function (index) {
            this.jsonData.items.splice(index, 1);
            this.selectedIndex = -1;
          },
          /**
           * 编辑器：选择图片
           * @param source
           * @param index
           */
          onEditorSelectImage: function (source, index, type = "image/") {
            parent.Fast.api.open(`general/attachment/select?element_id=&multiple=true&mimetype=${type}*`, __('Choose'), {
              callback: function (data) {
                if (data.multiple) {
                  source[index] = data.url;
                }
              }
            });
          },
          /**
           * 编辑器：编辑富文本
           * @param source
           * @param index
           */
          onEditorRichtext: function (source) {
            localStorage.setItem("EditorRichtextdata", source['content']);
            Fast.api.open('wdsxh/diy_page/editor', __('Edit'), {
              callback: function (data) {
                if (data) {
                  source['content'] = data;
                }
              }
            });
          },
          /**
           * 编辑器：选择URL
           * @param source
           * @param index
           */
          onEditorSelecturl: function (source) {
            var _this = this;

            var call = function(type, row){
              source['link'] = null;
              if (type === 'Inlay'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Phone'){
                source['link'] = {type:type,title:row.name,phone:_this.dialogform.param1};
              }else if(type === 'Custom'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Member'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Article'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Company'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Activity'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'WXMp'){
                source['link'] = {type:type,title:row.name,appid:_this.dialogform.param1,path:_this.dialogform.param2};
              }else if(type === 'Outside'){
                source['link'] = {type:type,title:row.name,url:_this.dialogform.param1 +_this.dialogform.param2};
              }else if(type === 'QQ'){
                source['link'] = {type:type,title:row.name,qq:_this.dialogform.param1};
              }else if(type === 'Copy'){
                source['link'] = {type:type,title:row.name,text:_this.dialogform.param1};
              }else if(type === 'notice'){
                source['link'] = {type:type,title:row.name,key:_this.dialogform.param1,data:_this.dialogform.param2};
              }

              _this.dialogSelecturl = false;
            }
            _this.fcall = call;
            _this.dialogform.param1 = '';
            _this.dialogform.param2 = '';
            $.post('wdsxh/diy_page/selectUrlPro', {}, function (result) {
              _this.dialogData = result.rows;
              _this.dialogSelecturl = true;
            });
          },
          /**
           * 编辑器：重置颜色
           * @param holder
           * @param attribute
           * @param color
           */
          onEditorResetColor: function (holder, attribute, color) {
            holder[attribute] = color;
          },

          /**
           * 编辑器：删除data元素
           * @param index
           * @param selectedIndex
           */
          onEditorDeleteData: function (index, selectedIndex) {
            if (this.jsonData.items[selectedIndex].data.length <= 1) {
              Toastr.error('至少保留一个组件');
              return false;
            }
            this.jsonData.items[selectedIndex].data.splice(index, 1);
          },

          /**
           * 编辑器：添加data元素
           */
          onEditorAddData: function () {
            // 新增data数据
            var newDataItem = $.extend(true, {}, defaultData[this.curItem.type].data[0]);
            this.curItem.data.push(newDataItem);
          },

          /**
           * 提交后端保存
           * @returns {boolean}
           */
          onSubmit: function () {
            if (this.jsonData.items.length <= 0) {
              Toastr.error('至少保留一个组件');
              return false;
            }
            var data = JSON.stringify(this.jsonData);
            $.post('', { data: data }, function (result) {
              if (result.code === 1) {
                parent.window.$(".btn-refresh").trigger("click");

                Toastr.success(result.msg);
                return setTimeout(() => {
                  Fast.api.close({});
                }, 1000);
              }
              return Toastr.error(result.msg);
            });
          }

        }
      });

      Controller.api.bindevent();
    },
    edit: function () {
      new Vue({
        el: '#diy',
        data: {
          jsonData: jsonData,
          selectedIndex: -1,
          defaultData: defaultData,
          curItem: {},
          // 选择url start
          dialogData: null,
          dialogSelecturl: false,
          currmenuidx: 'Inlay',//索引
          fcall: null,// 回调
          dialogform: {
            param1: '',
            param2: '',
          }
          // 选择url end
        },
        error: '',
        methods: {
          /**
           * 新增组件
           * @param key
           */
          handleAdd: function (key) {

            if (!this.onCheckAddwebview(key)) {
              return false;
            }


            // 复制默认diy组件数据
            var data = $.extend(true, {}, defaultData[key]);
            // 新增到diy列表数据
            this.jsonData.items.push(data);

            // 编辑当前选中的元素
            this.handleEdit(this.jsonData.items.length - 1);
          },

          /**
           * 拖动diy元素更新当前索引
           * @param e
           */
          onDragItemEnd: function (e) {
            this.handleEdit(e.newIndex);
          },

          /**
           * 验证新增Diy组件
           * @param key
           */
          onCheckAddwebview: function (key) {
            // 验证webview组件只能存在一个
            if (key === 'webview') {
              if (this.jsonData.items.length != 0) {
                Toastr.error('webview不能和其他组件一起使用');
                return false;
              }
            } else {
              for (var index in this.jsonData.items) {
                if (this.jsonData.items.hasOwnProperty(index)) {
                  var item = this.jsonData.items[index];
                  if (item.type === 'webview') {
                    Toastr.error('webview不能和其他组件一起使用');
                    return false;
                  }
                }
              }
            }
            return true;
          },

          /**
           * 编辑当前选中的Diy元素
           * @param index
           */
          handleEdit: function (index) {
            // 记录当前选中元素的索引
            this.selectedIndex = index;
            // 当前选中的元素数据
            this.curItem = this.selectedIndex == -1 ? this.jsonData.page : this.jsonData.items[this.selectedIndex];
            // 设置选中标签
            if (!this.curItem.activeName) this.curItem.activeName = "first"
          },

          // 获取当前时间
          getCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
          },

          /**
           * 复制diy元素
           * @param index
           */
          onCopyItem: function (index) {
            var _this = this;
            // 复制默认diy组件数据
            var data = $.extend(true, {}, _this.jsonData.items[index]);
            // 新增到diy列表数据
            this.jsonData.items.push(data);

            // 编辑当前选中的元素
            this.handleEdit(this.jsonData.items.length - 1);
          },
          /**
           * diy元素上移
           * @param index
           */
          onMoveUp: function (index) {
            if (0 == index) {
              return;
            }
            this.jsonData.items[index] = this.jsonData.items.splice(index - 1, 1, this.jsonData.items[index])[0];
            this.selectedIndex = index - 1
          },

          /**
           * diy元素下移
           * @param index
           */
          onMoveDown: function (index) {
            if (this.jsonData.items.length - 1 == index) {
              return;
            }
            this.jsonData.items[index] = this.jsonData.items.splice(index + 1, 1, this.jsonData.items[index])[0];
            this.selectedIndex = index + 1
          },
          /**
           * 删除diy元素
           * @param index
           */
          onDeleleItem: function (index) {
            this.jsonData.items.splice(index, 1);
            this.selectedIndex = -1;
          },
          /**
           * 编辑器：选择图片
           * @param source
           * @param index
           */
          onEditorSelectImage: function (source, index, type = "image/") {
            parent.Fast.api.open(`general/attachment/select?element_id=&multiple=true&mimetype=${type}*`, __('Choose'), {
              callback: function (data) {
                if (data.multiple) {
                  source[index] = data.url;
                }
              }
            });
          },
          /**
           * 编辑器：编辑富文本
           * @param source
           * @param index
           */
          onEditorRichtext: function (source) {
            localStorage.setItem("EditorRichtextdata", source['content']);
            Fast.api.open('wdsxh/diy_page/editor', __('Edit'), {
              callback: function (data) {
                if (data) {
                  source['content'] = data;
                }
              }
            });
          },
          /**
           * 编辑器：选择URL
           * @param source
           * @param index
           */
          onEditorSelecturl: function (source) {
            var _this = this;

            var call = function (type, row) {
              source['link'] = null;
              if (type === 'Inlay'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Phone'){
                source['link'] = {type:type,title:row.name,phone:_this.dialogform.param1};
              }else if(type === 'Custom'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Member'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Article'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Company'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'Activity'){
                source['link'] = {type:type,title:row.title,path:row.path};
              }else if(type === 'WXMp'){
                source['link'] = {type:type,title:row.name,appid:_this.dialogform.param1,path:_this.dialogform.param2};
              }else if(type === 'Outside'){
                source['link'] = {type:type,title:row.name,url:_this.dialogform.param1 +_this.dialogform.param2};
              }else if(type === 'QQ'){
                source['link'] = {type:type,title:row.name,qq:_this.dialogform.param1};
              }else if(type === 'Copy'){
                source['link'] = {type:type,title:row.name,text:_this.dialogform.param1};
              }else if(type === 'notice'){
                source['link'] = {type:type,title:row.name,key:_this.dialogform.param1,data:_this.dialogform.param2};
              }

              _this.dialogSelecturl = false;
            }
            _this.fcall = call;
            _this.dialogform.param1 = '';
            _this.dialogform.param2 = '';
            $.post('wdsxh/diy_page/selectUrlPro', {}, function (result) {
              _this.dialogData = result.rows;
              _this.dialogSelecturl = true;
            });
          },
          /**
           * 编辑器：重置颜色
           * @param holder
           * @param attribute
           * @param color
           */
          onEditorResetColor: function (holder, attribute, color) {
            holder[attribute] = color;
          },

          /**
           * 编辑器：删除data元素
           * @param index
           * @param selectedIndex
           */
          onEditorDeleteData: function (index, selectedIndex) {
            if (this.jsonData.items[selectedIndex].data.length <= 1) {
              Toastr.error('至少保留一个组件');
              return false;
            }
            this.jsonData.items[selectedIndex].data.splice(index, 1);
          },

          /**
           * 编辑器：添加data元素
           */
          onEditorAddData: function () {
            // 新增data数据
            var newDataItem = $.extend(true, {}, defaultData[this.curItem.type].data[0]);
            this.curItem.data.push(newDataItem);
          },

          /**
           * 提交后端保存
           * @returns {boolean}
           */
          onSubmit: function () {
            if (this.jsonData.items.length <= 0) {
              Toastr.error('至少保留一个组件');
              return false;
            }
            for(var i in this.jsonData.items) {
              this.jsonData.items[i].activeName = undefined
            }
            var data = JSON.stringify(this.jsonData);
            $.post('', { data: data }, function (result) {
              if (result.code === 1) {
                parent.window.$(".btn-refresh").trigger("click");

                Toastr.success(result.msg);
                return setTimeout(() => {
                  Fast.api.close({});
                }, 1000);
              }
              return Toastr.error(result.msg);
            });
          }

        }
      });
      Controller.api.bindevent();
    },
    editor: function () {
      document.getElementById('textareacallback').value = localStorage.getItem("EditorRichtextdata");
      Controller.api.bindevent();
      $(document).on('click', '.btn-callback', function () {
        Fast.api.close($("textarea[name=textareacallback]").val());
      });
      $(document).on('click', '.btn-cancel', function () {
        Fast.api.close();
      });
    },
    api: {
      bindevent: function () {
        Form.api.bindevent($("form[role=form]"));
      }
    }
  };
  return Controller;
});
